import { useState, useEffect } from "react";
import { Button, message, Form, Input, Space, Select } from "antd";
import { useModel } from "umi";
import { useReactive } from "ahooks";

import { useOrganizationMember } from "@share-code/public";

const CreatePlatformRole = ({ reloadData, testers }) => {
    const { remoteData, graphqlFetch } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");
    const [form] = Form.useForm();
    const [submitLoading, setSubmitLoading] = useState(false);
    const { loadAllOrganizationMembersByOmAust } = useOrganizationMember(graphqlFetch);

    const state = useReactive({
        loading: false,
        members: [],
        testers: [],
    });

    const loadOrgMembers = async () => {
        setSubmitLoading(true);
        let res = await loadAllOrganizationMembersByOmAust("已认证");
        if (res) state.members = res.filter((item) => testers.findIndex((_item) => _item.miIdno === item.omIdnu) === -1);
        setSubmitLoading(false);
    };

    useEffect(() => {
        loadOrgMembers();
    }, []);

    const onFinish = async (values) => {
        setSubmitLoading(true);
        let saveData = state.members.find((item) => item.omUuid === values.omUuid);
        if (!saveData.omIdnu) return message.error("请联系该人员进行身份认证，并同步信息到组织！");
        let res = await remoteData({
            object: "bnt-application-resource-center-service",
            serviceName: "/developer/members/addTester",
            params: saveData,
        });
        if (res) {
            message.success("成功添加开发人员");
            await reloadData();
            form.resetFields();
            onCloseGlobalModal();
        }
        setSubmitLoading(false);
    };

    return (
        <div style={{ padding: "0 30px 30px 30px" }}>
            <Form form={form} onFinish={onFinish} layout="vertical">
                <Form.Item label="人员名称" name="omUuid" rules={[{ required: true }]}>
                    <Select
                        allowClear
                        showSearch
                        placeholder="请输入人员名称"
                        optionFilterProp="children"
                        fieldNames={{ label: "omName", value: "omUuid" }}
                        filterOption={(input, option) => option?.omName.indexOf(input) !== -1}
                        options={state.members}
                    />
                </Form.Item>

                <Form.Item style={{ textAlign: "center" }}>
                    <Space>
                        <Button loading={submitLoading} type="primary" htmlType="submit">
                            添加
                        </Button>
                        <Button loading={submitLoading} htmlType="button" onClick={() => onCloseGlobalModal()}>
                            取消
                        </Button>
                    </Space>
                </Form.Item>
            </Form>
        </div>
    );
};

export default CreatePlatformRole;
